﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Runtime.Serialization.Json;

namespace SampleKeyValueDemo
{
    public class SolidStateStore<T> : IKeyValueDataStore<T>
    {

        private DirectoryInfo storeDir {
            get
            {

                var d = HttpContext.Current.Server.MapPath("~/data/" + typeof(T));
                var dir = new DirectoryInfo(d);
                if (!dir.Exists)
                {
                    dir.Create();
                }
                return dir;
            }
        }

        private string GPath(string key)
        {
            return Path.Combine(this.storeDir.FullName, key + ".js");
        }

        public void Set(string key, T val)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using(var fs = new FileStream(GPath(key), FileMode.Create)){
                serializer.WriteObject(fs, val);
            }
        }

        public T Get(string key)
        {
            var serializer = new DataContractJsonSerializer(typeof(T));
            using (var fs = new FileStream(GPath(key), FileMode.Open))
            {
                return (T)serializer.ReadObject(fs);
            }
        }

        public void Remove(string key)
        {
            File.Delete(this.GPath(key));
        }
    }
}